// DeviceDlg.cpp : implementation file
//

#include "stdafx.h"
#include "ADK.h"
#include "DeviceDlg.h"
#include "ADKDlg.h"

// CDeviceDlg dialog

IMPLEMENT_DYNAMIC(CDeviceDlg, CDialog)

CDeviceDlg::CDeviceDlg(CWnd* pParent /*=NULL*/)
: CDialog(CDeviceDlg::IDD, pParent)
{

}

CDeviceDlg::~CDeviceDlg()
{
}

void CDeviceDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_TREE_NEW_DEVICE, m_treeDevices);
}

BOOL CDeviceDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	LoadSysConfig();

	return TRUE;
}

BEGIN_MESSAGE_MAP(CDeviceDlg, CDialog)
	ON_NOTIFY(TVN_SELCHANGED, IDC_TREE_NEW_DEVICE, &CDeviceDlg::OnSelDevicechanged)
END_MESSAGE_MAP()

// CDeviceDlg message handlers
int CDeviceDlg::LoadSysConfig()
{
	int nCount = 0, nSubCount = 0;
	CString strSection(_T("")), strKey(_T(""));
	CString strFileName, strDeviceName, strDeviceType;

	HTREEITEM hItemParent;

	CADKDlg *pDlg = (CADKDlg *)AfxGetApp()->m_pMainWnd;
	strFileName = pDlg->GetCurrentDir() + PR_OPOS_SYSTEM_DEFINITION;
	strSection = _T("Device");
	strKey = _T("Count");
	nCount = GetPrivateProfileInt(
		(LPCTSTR)strSection,
		(LPCTSTR)strKey,
		0,
		(LPCTSTR)strFileName);

	for (int i = 0; i < nCount; i++)
	{
		strSection = _T("Device");
		strKey.Format(_T("D%02d"), i);
		GetPrivateProfileString(
			strSection, 
			strKey,
			strDeviceName,
			strDeviceName.GetBuffer(20),
			20,
			strFileName);

		strDeviceName.ReleaseBuffer();
		hItemParent = m_treeDevices.InsertItem(strDeviceName);

		strSection = strDeviceName;
		strKey = _T("Count");
		nSubCount = GetPrivateProfileInt(
			strSection,
			strKey,
			0,
			strFileName);
		for(int j=0; j<nSubCount; j++)
		{
			strKey.Format(_T("%02d"), j);
			GetPrivateProfileString(
				strSection,
				strKey,
				strDeviceType,
				strDeviceType.GetBuffer(20),
				20,
				strFileName);
			strDeviceType.ReleaseBuffer();	
			m_treeDevices.InsertItem(strDeviceType, hItemParent);

		}
	}

	m_treeDevices.Expand(hItemParent,TVE_EXPAND);

	return 0;
}
void CDeviceDlg::OnSelDevicechanged(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMTREEVIEW pNMTreeView = reinterpret_cast<LPNMTREEVIEW>(pNMHDR);
	// TODO: Add your control notification handler code here
	
	HTREEITEM hSelItem = m_treeDevices.GetSelectedItem();
	HTREEITEM hParentItem = m_treeDevices.GetParentItem(hSelItem);
	HTREEITEM hChildItem = m_treeDevices.GetChildItem(hSelItem);
	if(hParentItem != NULL && hChildItem == NULL)
	{
		m_strDeviceName = m_treeDevices.GetItemText(hSelItem);
		m_strDeviceClass = m_treeDevices.GetItemText(hParentItem);

		GetDlgItem(IDOK)->EnableWindow();
	}
	else
		GetDlgItem(IDOK)->EnableWindow(FALSE);

	*pResult = 0;

}
